/**
 * Created by Skipper on 2017/5/8.
 */
import React from 'react';
import {PropTypes} from 'prop-types'
// import {Set} from 'immutable'
import {GoogleMap, withGoogleMap, Marker, InfoWindow, Polyline} from "react-google-maps";
import withScriptjs from "react-google-maps/lib/async/withScriptjs";
import InfoBox from "react-google-maps/lib/addons/InfoBox";
import {gcj02towgs84, wgs84togcj02} from './coordtransform';
import WebsocketComp from './websocket';
import {system_status_flag, infosConst} from './commonData';
import reqwest from 'reqwest';
import mock from '../mock/mock'

reqwest({
  // url: 'https://cloud.xyitech.com/item/search?token=MTEwIzE1MDY2NTc2ODBAY2xvdWQueHlpdGVjaC5jb20jdmp5d1JWWHRDengrWW9MZnAxZisxUTlTUExrPQ==&page_size=10&page_no=0&v=debug',
  url: 'https://cloud.xyitech.com/store/search/',
  type: 'json',
  method: 'get',
  error: function (err) {
    console.log('Ops,发生错误了', err)
  },
  success: function (resp) {
    console.log('啦啦啦~mock数据是', resp);
  }
});
const FLIGHTICON = require('../images/flight.png');
const UUSERLOCATION = require('../images/user-location.png');
const MARKERBLUE = require('../images/mark-bs.png');
const ROUTE_START = require('../images/route-start.png');
// const ROUTE_START = require('../images/toothpaste.gif');
const ROUTE_END = require('../images/route-end.png');
const AsyncMonitorFlightsGoogleMap = withScriptjs(
  withGoogleMap(
    props => (
      <GoogleMap
        ref={props.onMapLoad}
        options={props.mapdefaultProps}
        defaultZoom={props.mapdefaultProps.zoom}
        defaultCenter={props.mapdefaultProps.center}
        center={props.center}
        onClick={props.onMapClick}
      >
        {
          props.flightMarker.map((marker, index) => {
            let onClick = () => props.onMarkerClick(marker);
            let onCloseClick = () => props.onCloseClick(marker);
            return (
              marker.isLast ? <Marker
                {...marker}
                onClick={onClick}
              >
                {
                  marker.showInfo && (
                    <InfoBox>
                      <div className="info-box">
                        距离终点
                        <span>{`${this.state.lastDistance}km`}</span>
                      </div>
                    </InfoBox>
                  )
                }
              </Marker> : <Marker {...marker} onClick={onClick}>
                {
                  marker.showInfo && (
                    <InfoWindow onCloseClick={onCloseClick}>
                      <div className="maarker-infowindow-container">
                        <p><span>{`Lon：${marker.position.lng}`}</span></p>
                        <p><span>{`Lat：${marker.position.lat}`}</span></p>
                        <p><span>{`编号：${marker.label.text}`}</span></p>
                      </div>
                    </InfoWindow>

                  )
                }
              </Marker>
            )
          })
        }
        {
          props.markers.map(marker => {
            let onClick = () => props.onMarkerClick(marker);
            let onCloseClick = () => props.onCloseClick(marker);
            return (
              <Marker
                {...marker}
                draggable={false}
                onClick={onClick}
              >
                {
                  (marker.showInfo) && (
                    <InfoWindow onCloseClick={onCloseClick}>
                      <div>
                        <strong>{marker.content}</strong>
                        <p><span>{`Lon：${marker.position.lng}`}</span></p>
                        <p><span>{`Lat：${marker.position.lat}`}</span></p>
                        <p><span>{`速度：${marker.v}`}</span></p>
                        <p><span>{`高度：${marker.alt}`}</span></p>
                        <p><span>{`编号：${marker.title}`}</span></p>
                        {
                          marker.data ? <p><span>{`距离终点：${marker.data.infos.local_position_ned}`}</span></p> : null
                        }
                      </div>
                    </InfoWindow>
                  )
                }
              </Marker>
            )
          })
        }
        <Polyline
          path={props.polylineArr}
          options={{
            strokeColor: '#ABABAB',
            strokeOpacity: 1,
            strokeWeight: 4,
            strokeStyle: "solid",
          }}
          key={Date.now()}
        />
      </GoogleMap>
    )
  )
)
export default class JetGoMaps extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isMapLoaded: false,
      mapdefaultProps: {
        center: {
          lat: 31.123456, lng: 119.123456
        },
        zoom: 8,
        disableDefaultUI: true,
        // zoomControl: false,
        // scaleControl: true
      },
      center: {
        lat: 31.123456, lng: 119.123456
      },

      airWaydatas: [],
      flightMarker: [],
      polylineArr: [],
      markers: [],

      isFullScreen: false,
      infos: infosConst,
      isFlightIDStatus: false,
      flightID: 'JetGo',

      duration: 0,
      lastDistance: 0,
      points: [],
      WSUrl: 'production'
    }
  }

  componentWillMount() {
  }

  componentDidMount() {
    let _this = this;
    window.document.addEventListener('message', function (e) {
      let data = JSON.parse(e.data);
      // alert(data + typeof data + typeof JSON.parse(data) + JSON.parse(data).type + JSON.parse(data).position);
      // alert(e.data + data + 'dddd' + typeof data + '类型试试');
      if (typeof data == 'string') {
        if (data == 'clearroute') {
          // alert(data)
          _this.clearRoute()
        } else if (data && (JSON.parse(data)).type && (JSON.parse(data)).type == 'usericon') {
          let usePosition = (JSON.parse(data)).position;
          let curPosition = wgs84togcj02(usePosition.lng, usePosition.lat);
          usePosition.lat = curPosition[1];
          usePosition.lng = curPosition[0];
          usePosition = {
            lng: curPosition[0],
            lat: curPosition[1]
          };
          _this.setState({
            center: usePosition,
            flightMarker: _this.state.flightMarker.map(marker => {
              if (marker.id == (JSON.parse(data)).type) {
                return {
                  ...marker,
                  position: usePosition,
                }
              }
              return marker;
            }),
            userLocation: usePosition,
          });
        }
      } else {
        // alert(e.data + data + 'dddd' + typeof data + '类型试试');
        _this.setState({
          airWaydatas: data,
          flightID: data.fid ? data.fid : 'JetGo',
          duration: data.duration,

          isFlightIDStatus: data.fid ? true : false,
          WSUrl: data.Environment ? data.Environment : 'production'
        });
        _this.handleRouteData(data);
      }
      // _this.getRouteData(e.data);
    })
  }

  handleMapClick = () => {
  };
  handleMapLoad = (map) => {
    this._mapComponent = map;
    if (map) {
      // let Newmap = new google.maps.Map();
      // console.log( 'map is ', map, map.getCenter());
      let bounds = map.getBounds;
      // console.log('bounds is ',bounds);

      this.setState({
        isMapLoaded: true,
        flightMarker: [
          ...this.state.flightMarker,
          {
            position: this.state.infos.isGPS ? {
              lat: this.state.infos.gps_raw.lat,
              lng: this.state.infos.gps_raw.lon
            } : {lat: 31.123456, lng: 119.123456},
            defaultAnimation: 2,
            draggable: false,
            key: Date.now(),
            icon: {
              url: UUSERLOCATION,
              scaledSize: new google.maps.Size(28, 28),
              size: new google.maps.Size(28, 28),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(14, 14),
              labelOrigin: new google.maps.Point(14, 12)
            },
            id: 'usericon'
          }],
        map: map,
      });
      // map.panTo({lat: 35.123456, lng: 119.123456})
      // map.panBy(-300,0)
      // console.log('getZoom',map.getZoom())

      // this.getAirwayDetails()
    }
  }

  /*****
   * 获取航路轨迹并显示在地图上
   */
  getAirwayDetails() {
    let _this = this;
    let url = 'http://jieyan.xyitech.com/route/search?token=MSMxNDg3MjExNzU1QGppZXlhbi54eWl0ZWNoLmNvbSNYTlFpWlpoM3IyVTNVTVk3K2hQQmp6bTZjMlk9&id=323';
    // console.log('请求数据是 ', url);
    fetch(url)
      .then(function (response) {
        return response.json()
      })
      .then(function (data) {
        // console.log(' data', data);
        if (data.err == 0) {
          if (data.msg.length != 0) {
            _this.handleRouteData(data.msg[0])
            // _this.handleRouteData([])
          }
        }
      })
      .catch(function (e) {
        console.log("Oops, error", e);
      });
  }


  handleRouteData(data) {
    let _this = this;
    // let routeData = _this.state.airWaydatas;
    let routeData = data;
    // alert('routeData  is ' + this.state.airWaydatas+this.state.flightID);
    // console.log('routeData is ', routeData)
    if (routeData.length == 0) {
      return false
    }
    let points = JSON.parse(routeData.detail).map(point => {
      let curPosition = wgs84togcj02(point.lng, point.lat);
      point.lat = curPosition[1];
      point.lng = curPosition[0];
      return point
    });
    let markerPoints = [];
    markerPoints.push(points[0])
    markerPoints.push(points[points.length - 1])
    // console.log('routeData  is ', routeData, '  points is ', points);
    // alert('routeData  is ' + routeData + '  points is ' + points);
    _this.setState({
      center: {
        lat: (points[0].lat + (points[points.length - 1]).lat) / 2,
        lng: (points[0].lng + (points[points.length - 1]).lng) / 2
      },
      markers: markerPoints.map((marker, index) => {
        if (index == 0) {
          return {
            position: {lat: marker.lat, lng: marker.lng},
            defaultAnimation: 2,
            draggable: false,
            key: index,
            icon: {
              url: ROUTE_START,
              scaledSize: new google.maps.Size(50, 50),
              size: new google.maps.Size(50, 50),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(25, 25),
              labelOrigin: new google.maps.Point(25, 25)
            },
            label: {
              text: ' ',
              color: '#fff'
            },
            title: index.toString(),
            showInfo: false,
            zIndex: 0,
            content: `欢迎来到${index.toString()}号空间站`,
            alt: marker.alt,
            v: marker.v,
          }
        }
        if (index == 1) {
          return {
            position: {lat: marker.lat, lng: marker.lng},
            defaultAnimation: 2,
            draggable: false,
            key: index,
            icon: {
              url: ROUTE_END,
              scaledSize: new google.maps.Size(20, 20),
              size: new google.maps.Size(20, 20),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(10, 10),
              labelOrigin: new google.maps.Point(10, 10)
            },
            label: {
              text: ' ',
              color: '#fff'
            },
            title: index.toString(),
            showInfo: false,
            zIndex: 0,
            content: `欢迎来到${index.toString()}号空间站`,
            alt: marker.alt,
            v: marker.v,
            data: this.state.infos,
            isLast: true,
          }
        }
      }),
      polylineArr: points.map(data => {
        return {lat: data.lat, lng: data.lng}
      }),
      points: points
    })
    let bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < points.length; i++) {
      bounds.extend({lat: points[i].lat, lng: points[i].lng});
    }
    let mapBounds = this.state.map.getBounds();
    // console.log('mapBounds  ', mapBounds, mapBounds.b.b, '  airWayBounds  ', bounds, bounds.b.b, '  markerPoints is ', markerPoints);
    this.state.map.fitBounds(bounds);
  }

  handleMarkerClick = (targetMarker) => {
    this.setState({
      flightMarker: this.state.flightMarker.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
    window.postMessage('这是WebView地图传递的数据', '*');
  }

  handleCloseClick = (targetMarker) => {
    this.setState({
      flightMarker: this.state.flightMarker.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),
    });
  }

  clearRoute() {
    let data = [];
    this.setState({
      markers: data.map((marker, index) => {
        if (index == 0) {
          return {
            position: {lat: marker.lat, lng: marker.lng},
            defaultAnimation: 2,
            draggable: false,
            key: index,
            icon: {
              url: ROUTE_START,
              scaledSize: new google.maps.Size(50, 50),
              size: new google.maps.Size(50, 50),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(25, 25),
              labelOrigin: new google.maps.Point(25, 25)
            },
            label: {
              text: ' ',
              color: '#fff'
            },
            title: index.toString(),
            showInfo: false,
            zIndex: 0,
            content: `欢迎来到${index.toString()}号空间站`,
            alt: marker.alt,
            v: marker.v,
          }
        }
        if (index == 1) {
          return {
            position: {lat: marker.lat, lng: marker.lng},
            defaultAnimation: 2,
            draggable: false,
            key: index,
            icon: {
              url: ROUTE_END,
              scaledSize: new google.maps.Size(20, 20),
              size: new google.maps.Size(20, 20),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(10, 10),
              labelOrigin: new google.maps.Point(10, 10)
            },
            label: {
              text: ' ',
              color: '#fff'
            },
            title: index.toString(),
            showInfo: false,
            zIndex: 0,
            content: `欢迎来到${index.toString()}号空间站`,
            alt: marker.alt,
            v: marker.v,
            data: this.state.infos,
            isLast: true,
          }
        }
      }),
      polylineArr: data.map(data => {
        return {lat: data.lat, lng: data.lng}
      }),
      points: data,
      flightMarker: [
        {
          position: this.state.userLocation,
          defaultAnimation: 'none',
          draggable: false,
          key: Date.now(),
          icon: {
            url: UUSERLOCATION,
            scaledSize: new google.maps.Size(28, 28),
            size: new google.maps.Size(28, 28),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(14, 14),
            labelOrigin: new google.maps.Point(14, 12)
          },
          id: 'usericon'
        }],
    })
  }

  /*****
   * websocket数据处理
   */
  websocketOnPen(arg) {
    // console.log('ws is ', arg);
    /*****WS存在且readyState==1，即已连接*****/
    if (arg.target.readyState && arg.target.readyState == 1) {
      // if (this.state.flightID != 'JetGo') {
      this.setState({
        isWebsocket: true,
        WebSocket: arg.target,
        flightMarker: [
          ...this.state.flightMarker,
          {
            position: this.state.infos.isGPS ? {
              lat: (this.state.infos.gps_raw.lat) * 1,
              lng: (this.state.infos.gps_raw.lon) * 1
            } : this.state.points.length > 1 ? {
              lat: this.state.points[this.state.points.length - 1].lat,
              lng: this.state.points[this.state.points.length - 1].lng
            } : {
              lat: 30.223456,
              lng: 120.123456
            },
            defaultAnimation: 2,
            draggable: false,
            key: Date.now(),
            icon: {
              url: FLIGHTICON,
              scaledSize: new google.maps.Size(50, 50),
              size: new google.maps.Size(50, 50),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(25, 25),
              labelOrigin: new google.maps.Point(25, 22)
            },
            label: {
              text: this.state.flightID ? this.state.flightID.toString() : 'JetGo',
              color: '#fff',
              fontSize: '12',
            },
            showInfo: false,
            id: this.state.flightID ? this.state.flightID.toString() : 'JetGo',
            baseMode: '人类不可居住',
            flightData: this.state.infos,
            title: this.state.flightID ? this.state.flightID.toString() : '捷雁无人机',
          }],
      })
      // } else {
      //   this.setState({
      //     isWebsocket: true,
      //     WebSocket: arg.target,
      //   })
      // }
    }
  }

  handleData(data) {
    let _this = this;
    if (data == 'undefined') {
      return;
    }
    let gettype = Object.prototype.toString;
    let resdt, msgid;
    let begin = 0;
    if (gettype.call(data) == '[object ArrayBuffer]') {
      resdt = new DataView(data);
      msgid = resdt.getUint8(begin);
    } else {
      resdt = JSON.parse(data);
      msgid = resdt[begin];
    }
    /*======飞机数据======*/
    // console.log('this.state.flightID', this.state.flightID)
    if (msgid == 3) {
      /*****相对坐标local_position_ned*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        begin += 1;
        let local_position_ned = {};
        local_position_ned['time_std_s'] = 0;
        local_position_ned['time_std_s'] = resdt[begin];
        local_position_ned['loseWSTime'] = local_position_ned['time_std_s'];
        begin += 1;
        local_position_ned['time_std_s'] = (local_position_ned['time_std_s']);
        local_position_ned['x'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['y'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['z'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vx'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vy'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vz'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['ultra_alt'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vz02'] = local_position_ned['vz'] * (-1);
        local_position_ned['dis_m'] = (resdt[begin] * 1).toFixed(1);
        begin += 1;
        _this.setState({
          infos: {
            ..._this.state.infos,
            local_position_ned: local_position_ned,
          },
          lastDistance: `${(this.state.duration - local_position_ned['dis_m']).toFixed(2)}km`
        });
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 5) {
      // console.log('msgid is ', msgid, '  isGPS ', _this.state.infos.isGPS,'  this.state.infos.gps_raw is ',this.state.infos.gps_raw);
      /*****GPS数据gps_raw*****/
      begin += 1;
      let id = resdt[begin]
      if (id == _this.state.flightID) {
        begin += 1;
        let gps_raw = {};
        gps_raw['time_std_s'] = 0;
        gps_raw['time_std_s'] = resdt[begin];
        let time_step = new Date().getTime() / 1000 - resdt[begin];
        let last_date = resdt[begin];
        begin += 1;
        gps_raw['fix_type'] = resdt[begin];
        begin += 1;
        let lat = parseFloat(resdt[begin]);
        gps_raw['lat_gps'] = lat;
        begin += 1;
        let lon = parseFloat(resdt[begin]);
        gps_raw['lon_gps'] = lon;
        begin += 1;
        let alt = parseFloat(resdt[begin]);
        gps_raw['alt_gps'] = alt;
        begin += 1;
        gps_raw['eph'] = resdt[begin];
        begin += 1;
        gps_raw['epv'] = resdt[begin];
        begin += 1;
        gps_raw['vel_gps'] = resdt[begin];
        begin += 1;
        gps_raw['vel_gps2'] = gps_raw['vel_gps'];
        gps_raw['cog'] = resdt[begin];
        begin += 1;
        gps_raw['satellites_visible'] = resdt[begin];
        begin += 1;
        let curPosition;
        if (_this.state.infos.isGPS) {
          curPosition = {
            lat: (wgs84togcj02(_this.state.infos.gps_raw.lon_gps, _this.state.infos.gps_raw.lat_gps)[1]) * 1,
            lng: (wgs84togcj02(_this.state.infos.gps_raw.lon_gps, _this.state.infos.gps_raw.lat_gps)[0]) * 1,
          };
        } else {
          curPosition = _this.state.flightMarker.position
        }
        _this.setState({
          infos: {
            ..._this.state.infos,
            gps_raw: gps_raw,
            time_step: time_step,
            last_date: last_date,
            isGPS: lat && lon ? true : false,
          },
          flightMarker: _this.state.flightMarker.map(marker => {
            // console.log('flightmarkerid is ', marker.id, '  GPS id ', id)
            if (marker.id == id || marker.id == 'JetGo') {
              return {
                ...marker,
                position: curPosition,
              };
            }
            return marker;
          }),
        });
      }
    } else {
      return
    }
  }

  handleErroData(data) {
    // console.log('websocket发生发生错误，请重试', data)
  }

  render() {
    return (
      <div className="map-container">
        {/*<div className="clear-btn" onClick={()=> {*/}
        {/*this.clearRoute()*/}
        {/*}}>清空航路*/}
        {/*</div>*/}
        <AsyncMonitorFlightsGoogleMap
          googleMapURL="http://ditu.google.cn/maps/api/js?v=3.exp&language=zh-CN&libraries=geometry,drawing&key=AIzaSyDEK4XKx_F2_R76kuxE_igcWbZpu1n14BQ"
          loadingElement={
            <div style={{height: `100%`}}>
            </div>
          }
          loading={this.state.loading}
          containerElement={
            <div style={{height: `100%`}}/>
          }
          mapElement={
            <div style={{height: `100%`}}>
            </div>
          }
          mapdefaultProps={this.state.mapdefaultProps}
          center={this.state.center}
          flightMarker={this.state.flightMarker}
          markers={this.state.markers}
          polylineArr={this.state.polylineArr}
          onMapLoad={this.handleMapLoad}
          onMarkerClick={this.handleMarkerClick}
          onCloseClick={this.handleCloseClick}
          onMapClick={this.handleMapClick}
        />
        {
          this.state.isMapLoaded && this.state.isFlightIDStatus ?
            <WebsocketComp url={`ws://jieyan.xyitech.com/control/create?v=${this.state.WSUrl}`}
                           onOpen={this.websocketOnPen.bind(this)}
                           onMessage={this.state.isWebsocket ? this.handleData.bind(this) : this.websocketOnPen.bind(this)}
                           onError={this.handleErroData.bind(this)}
                           binaryType='arraybuffer'
                           debug={true}/> : ''
        }
      </div>
    );
  }
}
